#!/usr/bin/perl


# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

use LWP::UserAgent;
use JSON;

use utf8;
use Encode qw( decode_utf8 );

# TODO: start tor
my $Url = $ARGV[0];
my $Json = JSON->new;
my $ua = LWP::UserAgent->new;

sub help{
    print "Number of book: download that book\nnext: Next page\nprevious: previous page\n";
    exit;
}

sub usage {
    print "USAGE: $0 query\n";
    exit;
}

if ($ARGV[0] eq "-h" || $ARGV[0] eq "--help") {
    &help;
}

if (not defined $ARGV[0]) {
    &usage;
}

$ua->proxy([qw(http https)] => 'socks://localhost:9050');
my $JSON = $ua->get('http://xfmro77i3lixucja.onion/search/?q='.$Url.'&fmt=json')->content;
my $x = 0;

$JSON = $Json->decode($JSON);


while(1) {



  a:
    $i = 0;
    for ($i; $i <= 19; $i++) {
        print $i . " - " . $JSON->{books}->[$i]->{title} . " --- " . $JSON->{books}->[$i]->{authors}->[0]." Language: " . $JSON->{books}->[$i]->{lang}."\n";

    }

    print "Selection: ";
    chomp(my $Selection = <STDIN>);

    if ($Selection eq 'next') {
        $x++;
        $JSON = $ua->get("http://xfmro77i3lixucja.onion/search/?q=$Url&p=$x&fmt=json")->content;
        $JSON = $Json->decode($JSON);
        goto a;

    }
    if ($Selection eq 'previous') {
        $x--;
        $JSON = $ua->get("http://xfmro77i3lixucja.onion/search/?q=$Url&p=$x&fmt=json")->content;
        $JSON = $Json->decode($JSON);
        goto a;

    }

    # Worst way to download a file

    my $Title = $JSON->{books}->[$Selection]->{title} . ".epub";
    my $DownloadUrl = "http://xfmro77i3lixucja.onion".$JSON->{books}->[$Selection]->{download};
    my $Book = $ua->get($DownloadUrl)->content;

    open(my $File,'>', decode_utf8($Title));
    print $File $Book;
    close $File;

    print "Downloaded\n";
    print "Download another? (Y/n)\n";
    chomp($Continue = <STDIN>);
    exit if $Continue eq "n";

}
